package stdio.costa.imoca.dao;

import java.util.List;

import javax.persistence.EntityManager;
import javax.persistence.NoResultException;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;

import org.springframework.stereotype.Component;

import stdio.costa.imoca.model.MocaUser;
import stdio.costa.imoca.model.Receiver;

@Component
public class ReceiverDao {

	@PersistenceContext
	private EntityManager entityManager;

	public void save(Receiver receiver) {
		entityManager.persist(receiver);
	}

	public Receiver update(Receiver receiver) {
		return entityManager.merge(receiver);
	}
	
	public void delete(Receiver receiver){
		entityManager.remove(receiver);
	}

	public Receiver findReceiverByNameAndSender(String name, MocaUser sender) {
		Query query = this.entityManager
				.createNamedQuery("findReceiverByNameAndSender")
				.setParameter("name", name).setParameter("sender", sender);
		try {
			return (Receiver) query.getSingleResult();
		} catch (NoResultException ne) {
			return null;
		}
	}

	public Receiver findReceiverByUuidAndSender(String uuid, MocaUser sender) {
		Query query = this.entityManager
				.createNamedQuery("findReceiverByUuidAndSender")
				.setParameter("uuid", uuid).setParameter("sender", sender);
		try {
			return (Receiver) query.getSingleResult();
		} catch (NoResultException ne) {
			return null;
		}
	}

	@SuppressWarnings("unchecked")
	public List<Receiver> findAllReceiversBySender(MocaUser sender) {

		Query query = this.entityManager.createNamedQuery(
				"findAllReceiversBySender").setParameter("sender", sender);
		try {
			return query.getResultList();
		} catch (NoResultException ne) {
			return null;
		}

	}
}
